package com.zhiyou100.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zhiyou100.model.User;
import com.zhiyou100.util.MD5Encryption;

public class UserInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		HttpSession session = request.getSession();
		Object o = session.getAttribute("user");
		if(o==null) {
			
			Cookie[] coo = request.getCookies();
			String email = null;
			String password = null;
			User user = null;
			for (Cookie cookie : coo) {
				if(cookie.getName().equals("email")) {
					email = cookie.getValue();
				}
				if(cookie.getName().equals("password")) {
					password = cookie.getValue();
				}
			}
			if(email!=null&&password!=null) {
				//模拟从数据库匹配账号和密码
				user = new User();
				user.setEmail(email);
				user.setPassword(password);
				request.getSession().setAttribute("user", user);
				return true;
			}else {
				System.out.println("你还没有登录");
				response.sendRedirect(request.getServletContext().getAttribute("BaseContext")+"front/index.jsp");
			}
			
		}else {
			System.out.println("用户已经登录");
			return true;
		}
		return false;
	}

}
